#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import traceback

from mie.xlogger.klog import klog
from mie.roar.roar import CallManager, CmdServer_Socket
from mie.roar.roarcmds import ExtCommands


class ConfMonitor(object):
    def __init__(self, conf, cmdServ=CmdServer_Socket):
        self.conf = conf
        self.conf.setmonitor(self.cfg_changed)
        self.cmdServ = cmdServ or CmdServer_Socket

        self.callman = None

        self.enable = None
        self.port = None

        self.cfg_changed(None)

    def cfg_changed(self, cookie):
        enable = self.conf.xget("roar/enable", 1)
        port = self.conf.xget("roar/port", 55000)

        if enable != self.enable:
            self.enable = enable
            if enable:
                try:
                    self.callman = CallManager()
                    self.cmdserv = self.cmdServ(self.callman, port)
                    self.cmdserv.start()
                    ExtCommands(self.callman, self.conf)
                except:
                    klog.e(traceback.format_exc())
            else:
                del self.cmdserv
                del self.callman
            return

        if port != self.port and self.enable:
            self.port = port

            del self.cmdserv
            self.cmdserv = CmdServer_Socket(self.callman, port)
            self.cmdserv.start()


ccmon = ConfMonitor
